package cn.lixu.product.service.impl;

import cn.lixu.basic.exception.BusinessException;
import cn.lixu.basic.service.IBaiduAiAuditService;
import cn.lixu.basic.service.impl.BaseServiceImpl;
import cn.lixu.product.domain.Product;
import cn.lixu.product.domain.ProductDetail;
import cn.lixu.product.mapper.ProductDetailMapper;
import cn.lixu.product.mapper.ProductMapper;
import cn.lixu.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
//只读，事务传播机制=SUPPORTS，有我就用，没有事务就不用
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductDetailMapper productDetailMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Override
    public void save(Product product) {

        Boolean textAudit = baiduAiAuditService.textAudit(product.getName());
        if (!textAudit) {
            throw new BusinessException("非法参数，请重新输入");
        }
        //先添加到ProductMapper，返回自增主键
        productMapper.save(product);

        //再添加到ProductDetailMapper
        ProductDetail productDetail = product.getProductDetail(); //获取ProductDetail对象
        productDetail.setProductId(product.getId());//对ProductDetail的productid进行重新赋值
        productDetailMapper.save(productDetail);//添加到productDetailMapper
    }

    @Override
    public void remove(Long id) {
        productMapper.remove(id);
        productDetailMapper.remove(id);
    }

    /**
     * 宠物上架
     *
     * @param ids
     */
    @Override
    public void onSale(List<Long> ids) {
        Date date = new Date();
        productMapper.onSale(ids, date);
    }

    /**
     * 宠物下架
     *
     * @param ids
     */
    @Override
    public void offSale(List<Long> ids) {
        Date date = new Date();
        productMapper.offSale(ids, date);
    }

    @Override
    public void update(Product product) {
        Boolean textAudit = baiduAiAuditService.textAudit(product.getName());
        if (!textAudit) {
            throw new BusinessException("非法参数，请重新输入");
        }
        productMapper.update(product);
        ProductDetail productDetail = productDetailMapper.loadById(product.getId());

        productDetailMapper.update(productDetail);

    }
}

